'use strict';

const utility = require('utility');
const uuid = require('uuid');
const Service = require('egg').Service;

class UserSvc extends Service {
  /*
   * 根据用户名列表查找用户列表
   * @param {Array} names 用户名列表
   * @return {Promise[users]} 承载用户列表的 Promise 对象
   */
  async getUsersByNames(names) {
    if (names.length === 0) {
      return [];
    }

    const query = {loginname: {$in: names}};
    return this.ctx.model.User.find(query).exec();
  }

  /*
   * 根据登录名查找用户
   * @param {String} loginName 登录名
   * @return {Promise[user]} 承载用户的 Promise 对象
   */
  getUserByLoginName(loginName) {
    const query = {loginname: loginName};
    return this.ctx.model.User.findOne(query).exec();
  }

  /*
   * 根据 githubId 查找用户
   * @param {String} githubId 登录名
   * @return {Promise[user]} 承载用户的 Promise 对象
   */
  getUserByGithubId(githubId) {
    const query = {githubId};
    return this.ctx.model.User.findOne(query).exec();
  }

  /*
   * 根据 token 查找用户
   * @param {String} token
   * @return {Promise[user]} 承载用户的 Promise 对象
   */
  getUserByToken(access_token) {
    const query = {access_token};
    return this.ctx.model.User.findOne(query).exec();
  }

  /*
   * 根据用户ID，查找用户
   * @param {String} id 用户ID
   * @return {Promise[user]} 承载用户的 Promise 对象
   */
  async getUserById(id) {
    if (!id) {
      return null;
    }

    return this.ctx.model.User.findOne({_id: id});
  }

  /*
   * 根据邮箱，查找用户
   * @param {String} email 邮箱地址
   * @return {Promise[user]} 承载用户的 Promise 对象
   */
  getUserByMail(email) {
    return this.ctx.model.User.findOne({email}).exec();
  }

  /*
   * 根据用户ID列表，获取一组用户
   * @param {Array} ids 用户ID列表
   * @return {Promise[users]} 承载用户列表的 Promise 对象
   */
  getUsersByIds(ids) {
    return this.ctx.model.User.find({_id: {$in: ids}}).exec();
  }

  /*
   * 根据关键字，获取一组用户
   * Callback:
   * - err, 数据库异常
   * - users, 用户列表
   * @param {String} query 关键字
   * @param {Object} opt 选项
   * @return {Promise[users]} 承载用户列表的 Promise 对象
   */
  getUsersByQuery(query, opt) {
    return this.ctx.model.User.find(query, '', opt).exec();
  }

  /*
   * 获取关键词能搜索到的用户数量
   * @param {String} query 搜索关键词
   */
  getCountByQuery(query) {
    return this.ctx.model.User.count(query).exec();
  }

  /*
   * 根据查询条件，获取一个用户
   * @param {String} name 用户名
   * @param {String} key 激活码
   * @return {Promise[user]} 承载用户的 Promise 对象
   */
  getUserByNameAndKey(loginname, key) {
    const query = {loginname, retrieve_key: key};
    return this.ctx.model.User.findOne(query).exec();
  }


  incrementScoreAndTopicCount(id, score, topic_count) {
    const query = {_id: id};
    const update = {$inc: {score, topic_count}};
    return this.ctx.model.User.findByIdAndUpdate(query, update).exec();
  }

  incrementScoreAndReplyCount(id, score, replyCount) {
    const query = {_id: id};
    const update = {$inc: {score: score, reply_count: replyCount}};
    return this.ctx.model.User.findByIdAndUpdate(query, update).exec();
  }

  incrementCollectTopicCount(id) {
    const query = {_id: id};
    const update = {$inc: {collect_topic_count: 1}};
    return this.ctx.model.User.findByIdAndUpdate(query, update).exec();
  }


  decrementCollectTopicCount(id) {
    const query = {_id: id};
    const update = {$inc: {collect_topic_count: -1}};
    return this.ctx.model.User.findByIdAndUpdate(query, update).exec();
  }

  newAndSave(name, loginname, pass, email, avatar_url, active, url, signature, default_boards, froms) {
    const user = new this.ctx.model.User();
    user.nickname = loginname;
    user.loginname = loginname;
    user.pass = pass;
    user.email = email;
    user.avatar_url = avatar_url;
    user.url = url;
    user.active = active || false;
    user.signature = signature;
    user.default_boards = default_boards;
    user.froms = froms;
    user.access_token = uuid.v4();

    return user.save();
  }

  makeGravatar(email) {
    // 头像服务坏了, 只能用固定的
    return 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/default.png';
    // let avatarHostName = 'http://dn-qiniu-avatar.qbox.me/avatar/';
    // let avatarHostName = 'http://sdn.geekzu.org/avatar/';
    // return avatarHostName + utility.md5(email.toLowerCase()) + '?d=identicon&s=48';
  }

  getGravatar(user) {
    return user.avatar_url || this.makeGravatar(user.email);
  }


  async updateUserInfoAfterImportTopics(topics) {
    const now = new Date();
    let groups = Object.values(topics.reduce((obj, item) => {
      if (obj[item.author_id]) {
        obj[item.author_id] = {
          author_id: item.author_id,
          last_create_title: item.title,
          last_create_content: item.content,
          last_createdAt: item.createdAt,
        }
      } else {
        obj[item.author_id] = {
          author_id: item.author_id,
          last_create_title: item.title,
          last_create_content: item.content,
          last_createdAt: item.createdAt,
        }
      }
      return obj;
    }, {}));

    await Promise.all(
      groups.map(async (g) => {
        const user_id = g.author_id;
        const success_import_count = g.count;
        const last_create_topic = {
          title: g.last_create_title,
          content: g.last_create_content,
          createdAt: g.last_createdAt,
        }

        await this.ctx.model.User.findByIdAndUpdate({_id: user_id},
          {
            $set: {last_click_tab_attention: now, last_create_topic: last_create_topic},
          }
        )

        // 处理缓存的原创标签(有些作者的标签太多了, 不缓存的话从db读取数据会很慢, 导入后需删除缓存, 重新计算)
        let original_tags_cache_key = `original_tags:${g.author_id}`;
        await this.service.cacheSvc.del(original_tags_cache_key);
      })
    );

  }


}

module.exports = UserSvc;
